﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TaskSimulator
{
    public partial class Form1 : Form
    {
        private string Uri
        {
            get
            {
                if(string.IsNullOrEmpty(textBox1.Text))
                {
                    return config.HTTPAddr + config.FilePath;
                }
                else
                {
                    return textBox1.Text;
                }
            }
        }


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Download();
            //Task t = DownloadAsync();
            WebDownloadAsync();
        }

        //同步下载(卡UI)
        public void Download()
        {
            HTTPHelper.HttpDownloadFile(Uri, @"D:\Work\Steam2.dll");
        }

        //异步下载
        public void DownloadByTask()
        {
            Task t = Task.Factory.StartNew(()=>
            {
                HTTPHelper.HttpDownloadFile(Uri, @"D:\Work\Steam2.dll");
            });
            //异常处理
            if(t.IsFaulted)
            {
                foreach(Exception ex in t.Exception.InnerExceptions)
                {
                    Console.WriteLine(ex.Message + "\r\n");
                }
                Console.ReadLine();
            }
            tbMessage.Text += "Download Completed! \r\n";
        }

        //异步下载之二async
        public async Task DownloadAsync()
        {
            tbMessage.Text += "Downloading... \r\n";

            await Task.Factory.StartNew(()=>
            {
                HTTPHelper.HttpDownloadFile(Uri, @"D:\Work\Steam2.dll");
            });
            //下载完成后执行以下语句
            tbMessage.Text += "Download Completed! \r\n";
        }

        //异步下载带进度条
        public void WebDownloadAsync()
        {
            tbMessage.Text += "Download begin... \r\n";
            HTTPHelper.WebClientDownFileAsync(
                Uri,
                @"D:\Work\Steam2.dll",
                (s, downloadProgressEA) =>
                    {
                        progressBar1.Minimum = 0;
                        progressBar1.Maximum = (int)downloadProgressEA.TotalBytesToReceive;
                        progressBar1.Value = (int)downloadProgressEA.BytesReceived;
                    },
                (ss, asyncCompletedEA) =>
                {
                    tbMessage.Text += "Download Completed! \r\n";
                });
        }
    }
}
